package chpt12;

/**
 * 测试事务处理1
 * 
 *
 */
import java.sql.*;
import java.util.Random;


public class TransactionTest1 {
	public static void main(String[] args) {
		String url = "jdbc:mysql://127.0.0.1:3306/demoDB?serverTimezone=Asia/Chongqing";
		String userName = "root";
		String pwd = "root123";
		String sql = "insert into students(sno, name, gpa)"
				+ " values(?, '陈某', ?)";
		try (Connection con = DriverManager.
				getConnection(url, userName, pwd);) {
			// con.setAutoCommit(false);
			int sqlNum = 6;
			Random rd = new Random();
			try (PreparedStatement pstmt = con.prepareStatement(sql);) {
				for (int i = 1; i <= sqlNum; i++) {
					if (i == 3) // 插入第3条记录时抛出异常
						throw new SQLException("插入时发生的异常！");
					pstmt.setString(1, "Js-"+i);
					double gpa = rd.nextDouble() * 4;
					pstmt.setDouble(2, gpa);
					pstmt.execute(); // 可以执行任何SQL
				}
				con.commit();
				System.out.println("事务已提交");
			} catch (SQLException e) {
				e.printStackTrace();
				try {
					System.out.println("事务正在回滚");
					con.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		} catch (SQLException e) {
			System.out.println("获取连接异常");
			e.printStackTrace();
		}
	}
}
